package models

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func GetInStorage(GoodParam map[string]interface{}) (error, []InStorage, int64) {
	var Message []InStorage
	page := GoodParam["page"].(int) //返回数据格式
	pageSize := GoodParam["limit"].(int)
	searchText := GoodParam["searchText"].(string)
	fmt.Println(page, pageSize, searchText)
	var total int64
	err := db.Table("in_storage").Where("inid like ?", "%"+searchText+"%").Order("inid ASC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&Message).Count(&total).Error //从数据库中查询信息

	return err, Message, total
}

func AddInStorage(c *gin.Context) (error, InStorage) {
	var Message InStorage
	err := c.ShouldBindJSON(&Message) //货物添加的货物信息
	if err != nil {
		fmt.Println(err.Error()) //后端查看错误
	}
	err = db.Table("in_storage").Select("inid", "num", "car", "intime", "tons", "category").Create(&Message).Error
	if err == nil {
		Calculate(Message.Category)
	}
	return err, Message
}

func UpInStorage(c *gin.Context) (error, InStorage) {
	var Message InStorage
	err := c.ShouldBindJSON(&Message)
	if err != nil {
		fmt.Println(err.Error())
		return err, InStorage{}
	}
	err = db.Table("in_storage").Where("inid = ?", Message.Inid).Updates(&Message).Error
	if err == nil {
		Calculate(Message.Category)
	}
	return err, Message
}

func DelInStorage(c *gin.Context) (error, InStorage) {
	var Message InStorage
	err := c.ShouldBindJSON(&Message) //数据绑定到结构体
	if err != nil {
		fmt.Println(err.Error())
		return err, InStorage{}
	}

	err = db.Table("in_storage").Where("inid = ?", Message.Inid).Delete(&Message).Error
	if err == nil {
		Calculate(Message.Category)
	}
	return err, Message
}
